﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.ExpedienteViewer;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Linq;
using MS.InformationManagement.Support;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint;
using MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls;
using System.Text;

namespace MS.InformationManagement.WP.DocumentCenter.ExpedienteViewer
{
    public partial class ExpedienteViewerUserControl : BaseControl, IExpedienteViewerView
    {
        #region fields

        ExpedienteViewerPresenter _presenter;
        Dictionary<string, string> _formUrl;

        #endregion

        #region Properties


        public bool EnableAddRemove
        {
            get {
                
                if (ViewState["AddRemoveEnable"] == null) {
                    ViewState["AddRemoveEnable"] = ExpedienteEntity.UsuarioAsignado.Equals(SPContext.Current.Web.CurrentUser.LoginName);
                }
                return Convert.ToBoolean(ViewState["AddRemoveEnable"]);
            }
        }
        public List<string> TipoUbicacion { get; set; }
        public List<Tomo> ListTomos { get; set; }

        public string IdExpediente
        {
            get { return Page.Request.QueryString["ExpedienteId"]; }
        }

        public Expediente ExpedienteEntity { get; set; }

        public IEnumerable<Radicado> Radicados { get; set; }

        public int TotalRecords
        {
            get;
            set;
        }

        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            GenerateRequiredJavascript();
            btnUpdate.AddLoader();
            btnAddVolume.AddLoader();

            txtAsunto.Required(ExceptionConstants.ERROR_CAMPO_NULO,"ValidationGroup", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            _formUrl = new Dictionary<string, string>();
            _formUrl = new Dictionary<string, string>();
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_ENTRADA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicado.aspx?strategy=edit&ListId={0}&ID={1}";
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicadoSalida.aspx?strategy=edit&ListId={0}&ID={1}";
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_INTERNO] = "/sites/docs/_layouts/MS.InformationManagement.WP/RadicadoInterno.aspx?strategy=edit&ListId={0}&ID={1}";
            _presenter = new ExpedienteViewerPresenter(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsPostBack) return;
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void update_action(object sender, EventArgs e)
        { 
            try
            {
                getExpediente();
                _presenter.HandleUpdate();
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void addvolume_action(object sender, EventArgs e)
        {
            try
            {
                _presenter.HandleCreateVolume();
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            try
            {
                Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ListTomos");
                ExpPorTomo.EnableAddRemove = EnableAddRemove;
                ExpPorTomo.LstTomos = ListTomos;
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ListTomos"] = ListTomos;
                //Expediente data
                lblAsignadoValue.Text = ExpedienteEntity.UsuarioAsignado;
                lblIdExpediente.Text = ExpedienteEntity.NúmeroExpediente;
                lblCodigoId.Text = ExpedienteEntity.Código;
                lblSerieId.Text = ExpedienteEntity.SerieName;
                lblSubSerieId.Text = ExpedienteEntity.SubserieName;
                lblFechaStartExpediente.Text = ExpedienteEntity.FechaInicial.HasValue ? ExpedienteEntity.FechaInicial.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : string.Empty;
                lblFechaEndExpediente.Text = ExpedienteEntity.FechaFinal.HasValue ? ExpedienteEntity.FechaFinal.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : string.Empty;
                txtAsunto.Text = ExpedienteEntity.Asunto;
                
                lblTotalFolios.Text = TotalRecords.ToString();
                lblTotalTomos.Text = ListTomos.Count.ToString();

                if (!EnableAddRemove)
                {
                    txtAsunto.Enabled = false;
                    btnAddVolume.Visible = false;
                    btnUpdate.Visible = false;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        public void ExpedienteUpdated()
        {
            HandleSuccess("Expediente actualizado exitosamente", null);
        }

        #endregion

        #region Private Methods

        private void getExpediente()
        {
            ExpedienteEntity = new Expediente();
            ExpedienteEntity.NúmeroExpediente = IdExpediente;
            ExpedienteEntity.Asunto = txtAsunto.Text;
        }

        private void GenerateRequiredJavascript()
        {
            StringBuilder javascriptBuilder = new StringBuilder("<script type='text/javascript'>");
            javascriptBuilder
                .Append("function exportItems(){")
                .Append(string.Format("var bID='{0}';", IdExpediente))
                .Append(string.Format("var url = '{0}/_layouts/Ms.InformationManagement.WP/ExportHandler.ashx?action=exportfolder&expID='+bID;", SPContext.Current.Web.Url))
                .Append("window.open(url, '_blank');}")
                .Append("</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "functions", javascriptBuilder.ToString(), false);
        }

        #endregion

    }
}
